"""
监控相关的Pydantic模式
"""

from pydantic import BaseModel, Field, validator
from typing import Optional, Dict, Any, List
from datetime import datetime
from enum import Enum


class MonitorType(str, Enum):
    """监控类型枚举"""
    KEYWORD = "keyword"
    SELLER = "seller"
    SHOP = "shop"


class MonitorStatus(str, Enum):
    """监控状态枚举"""
    PENDING = "pending"
    ACTIVE = "active"
    EXPIRED = "expired"
    STOPPED = "stopped"
    ERROR = "error"


class MonitorConditions(BaseModel):
    """监控条件模式"""
    # 关键词监控条件
    keyword: Optional[str] = Field(None, max_length=200, description="监控关键词")
    include_description: Optional[bool] = Field(True, description="是否包含商品描述")

    # 卖家监控条件
    seller_id: Optional[str] = Field(None, max_length=100, description="卖家ID")
    seller_name: Optional[str] = Field(None, max_length=200, description="卖家名称")

    # 店铺监控条件
    product_id: Optional[str] = Field(None, max_length=100, description="店铺商品ID（用于获取店铺信息）")
    shop_name: Optional[str] = Field(None, max_length=200, description="店铺名称")
    
    @validator('keyword')
    def validate_keyword(cls, v, values):
        if v is not None:
            v = v.strip()
            if len(v) < 2:
                raise ValueError('关键词长度不能少于2个字符')
            if len(v) > 200:
                raise ValueError('关键词长度不能超过200个字符')
        return v


class MonitorCreate(BaseModel):
    """监控创建模式"""
    monitor_type: MonitorType = Field(..., description="监控类型")
    name: Optional[str] = Field(None, max_length=200, description="监控任务名称")
    description: Optional[str] = Field(None, max_length=1000, description="监控描述")
    conditions: MonitorConditions = Field(..., description="监控条件")
    duration_hours: Optional[int] = Field(24, ge=1, le=168, description="监控时长（小时）")
    
    @validator('conditions')
    def validate_conditions(cls, v, values):
        monitor_type = values.get('monitor_type')

        if monitor_type == MonitorType.KEYWORD:
            if not v.keyword:
                raise ValueError('关键词监控必须提供关键词')
        elif monitor_type == MonitorType.SELLER:
            if not v.seller_id and not v.seller_name:
                raise ValueError('卖家监控必须提供卖家ID或卖家名称')
        elif monitor_type == MonitorType.SHOP:
            if not v.product_id and not v.shop_name:
                raise ValueError('店铺监控必须提供商品ID或店铺名称')

        return v
    
    @validator('name')
    def generate_name_if_empty(cls, v, values):
        if not v and 'conditions' in values and 'monitor_type' in values:
            monitor_type = values['monitor_type']
            conditions = values['conditions']

            if monitor_type == MonitorType.KEYWORD and conditions.keyword:
                v = f"关键词监控: {conditions.keyword}"
            elif monitor_type == MonitorType.SELLER and conditions.seller_name:
                v = f"卖家监控: {conditions.seller_name}"
            elif monitor_type == MonitorType.SHOP and conditions.shop_name:
                v = f"店铺监控: {conditions.shop_name}"
            else:
                v = f"{monitor_type.value}监控"

        return v


class MonitorUpdate(BaseModel):
    """监控更新模式"""
    name: Optional[str] = Field(None, max_length=200, description="监控任务名称")
    description: Optional[str] = Field(None, max_length=1000, description="监控描述")
    is_active: Optional[bool] = Field(None, description="是否激活")


class MonitorResponse(BaseModel):
    """监控响应模式"""
    id: int = Field(..., description="监控任务ID")
    user_id: int = Field(..., description="用户ID")
    monitor_type: MonitorType = Field(..., description="监控类型")
    name: str = Field(..., description="监控任务名称")
    description: Optional[str] = Field(None, description="监控描述")
    conditions: Dict[str, Any] = Field(..., description="监控条件")
    status: MonitorStatus = Field(..., description="监控状态")
    is_active: bool = Field(..., description="是否激活")
    duration_hours: int = Field(..., description="监控时长（小时）")
    
    # 时间信息
    started_at: Optional[datetime] = Field(None, description="开始时间")
    expires_at: Optional[datetime] = Field(None, description="过期时间")
    created_at: datetime = Field(..., description="创建时间")
    updated_at: datetime = Field(..., description="更新时间")
    last_check_at: Optional[datetime] = Field(None, description="最后检查时间")
    
    # 统计信息
    total_found: int = Field(..., description="发现商品总数")
    total_notified: int = Field(..., description="通知发送总数")
    
    # 错误信息
    error_message: Optional[str] = Field(None, description="错误信息")
    error_count: int = Field(..., description="错误次数")
    
    # 扩展信息
    remaining_hours: Optional[float] = Field(None, description="剩余监控时间（小时）")
    is_expired: bool = Field(..., description="是否已过期")
    
    class Config:
        from_attributes = True


class MonitorStatistics(BaseModel):
    """监控统计模式"""
    monitor_id: int = Field(..., description="监控任务ID")
    total_found: int = Field(..., description="发现商品总数")
    total_notified: int = Field(..., description="通知发送总数")
    total_notifications: int = Field(..., description="通知记录总数")
    clicked_notifications: int = Field(..., description="点击通知数")
    click_rate: float = Field(..., description="点击率（%）")
    processed_today: int = Field(..., description="今日处理数量")
    last_check: Optional[str] = Field(None, description="最后检查时间")
    
    # 效果分析
    avg_daily_found: float = Field(..., description="日均发现商品数")
    notification_rate: float = Field(..., description="通知率（%）")
    user_engagement: float = Field(..., description="用户参与度（%）")


class MonitorListResponse(BaseModel):
    """监控列表响应模式"""
    monitors: List[MonitorResponse] = Field(..., description="监控列表")
    total: int = Field(..., description="总数量")
    active_count: int = Field(..., description="活跃监控数")
    expired_count: int = Field(..., description="过期监控数")
    error_count: int = Field(..., description="错误监控数")


class MonitorActionRequest(BaseModel):
    """监控操作请求模式"""
    action: str = Field(..., description="操作类型: start/stop/restart")
    reason: Optional[str] = Field(None, max_length=500, description="操作原因")


class MonitorActionResponse(BaseModel):
    """监控操作响应模式"""
    monitor_id: int = Field(..., description="监控任务ID")
    action: str = Field(..., description="执行的操作")
    success: bool = Field(..., description="是否成功")
    message: str = Field(..., description="操作结果消息")
    new_status: Optional[MonitorStatus] = Field(None, description="新状态")
    expires_at: Optional[datetime] = Field(None, description="新的过期时间")
